'use strict';

const Controller = require('egg').Controller;

class ConversationController extends Controller {
  async getConversationList() {
    const ctx = this.ctx;
    const token = ctx.request.header.token;
    const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
    try {
      const user = await ctx.service.user.getUserByName(decode.username);
      const { id, permission } = user;
      let filterObj = {};
      if (permission === 3) { // 普通用户
        filterObj = { user_id: id };
      }

      const conversationList = await ctx.service.conversation.getConversationList(user, filterObj);
      this.ctx.body = {
        code: 200,
        conversation_list: conversationList,
      };
    } catch (e) {
      this.ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }

  async getConversationById() {
    const ctx = this.ctx;
    const data = ctx.request.body;
    const { conversation_id } = data;
    try {
      const conversation = await ctx.service.conversation.getConversationById(conversation_id);
      ctx.body = {
        code: 200,
        conversation,
      };
    } catch (e) {
      ctx.body = {
        code: 500,
        msg: '服务器错误',
      };
    }
  }

  async postMessage() { // 用户向客服发的第一句话，通过http请求发出，一般代表的是用户想要问的问题。
    const ctx = this.ctx;
    const app = this.app;
    const data = ctx.request.body;
    const baseStaffId = ctx.state.baseStaffId;
    const nsp = app.io.of('/manager');

    // 拿到数据后，判断是否为客服，并且生成一个工单
    try {
      const { user_id, another_user_id, content, content_type } = data;

      if (Number(another_user_id) === baseStaffId) { // 如果是基础客服的话，询问是否已有该工单，如果没有的话，则创建工单

        const conversation = await ctx.service.conversation.getConversationByUserId(user_id, another_user_id);
        if (!conversation) { // 没有工单，或者工单已经结束，创建工单
          // 判断是否需要重新创建会话
          const newConversation = await ctx.service.conversation.createConversation(user_id, another_user_id);
          const { id } = newConversation;
          await ctx.service.conversationInfo.createConversationInfo(id, user_id, content, content_type);
          // 设置 newsContent
          await ctx.service.conversation.setNewsContent(id, content, content_type);

          const result = await ctx.service.conversation.getConversationById(id);

          await nsp.emit('manager', {
            type: 1, // 有新工单来了
          }); // 通知所有客服需要更新消息列表

          ctx.body = {
            code: 200,
            msg: '排队中，请稍后',
            conversation: result,
          };
          return;
        }

        const { id } = conversation;
        await ctx.service.conversationInfo.createConversationInfo(id, user_id, content, content_type);
        await ctx.service.conversation.setNewsContent(id, content, content_type);
        const result = await ctx.service.conversation.getConversationById(id);
        ctx.body = {
          code: 200,
          conversation: result,
        };
        return;
      }
      ctx.body = {
        code: 200,
        msg: '收到数据了，但是待处理中',
      };
    } catch (e) {
      ctx.body = {
        code: 500,
        msg: '服务器错误',
      };
    }
  }

  async getConversationInfos() {
    const ctx = this.ctx;
    const data = ctx.request.body;
    const { conversation_id } = data;
    try {
      const infos = await ctx.service.conversationInfo.getConversationInfos(conversation_id);

      ctx.body = {
        data: infos,
        code: 200,
      };

    } catch (e) {
      ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }

  }

  async getAllConversationInfosWithStaff() { // 获取一个用户下所有与客服的会话记录
    const ctx = this.ctx;
    const data = ctx.request.body;
    const { user_id } = data;
    try {
      const infos = await ctx.service.conversationInfo.getAllConversationInfosWithStaff(user_id);
      ctx.body = {
        data: infos,
        code: 200,
      };
    } catch (e) {
      ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }

  async endTicket() { // 结单
    const ctx = this.ctx;
    const app = this.app;
    const data = ctx.request.body;
    const nsp = app.io.of('/');

    const { conversation_id, staff_id } = data;
    try {
      await ctx.service.conversation.endTicket(conversation_id);
      const conversation = await ctx.service.conversation.getConversationById(conversation_id);

      // 需要添加一个评价窗口
      await ctx.service.conversationInfo.createConversationInfo(conversation_id, staff_id, '0', 10);

      // 给该客服的工单数中添加添加一个数
      await ctx.service.user.endTicket(staff_id);

      await nsp.emit(`conversation_${conversation_id}`, {
        msg: '结单成功',
        type: 1, // 结单
      });

      ctx.body = {
        code: 200,
        conversation,
        msg: '结单成功',
      };
    } catch (e) {
      ctx.body = {
        code: 500,
        msg: '服务端出错',
      };
    }
  }
}

module.exports = ConversationController;
